using Microsoft.VisualBasic.ApplicationServices;
using System.Configuration;
using System.Diagnostics;
using System.DirectoryServices.ActiveDirectory;
using System.Globalization;
using System.IO;
using System.IO.Ports;
using System.Resources.Extensions;
using System.Security.Policy;
using System.Text;
using System.Text.Unicode;
using System.Xml.Linq;
using WaterQualityReportSystem;
using WaterQualityReportSystem.models;
using WaterQualityReportSystem.utils;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace WinFormsApp2
{
    public partial class MainForm : Form
    {
        private DeviceData deviceData = new DeviceData();
        private SerialPort serialPort = null;
        private StringBuilder sb = null;
        private RestClient restClient = null;
        private Byte[] buffers;
        //private bool isReadingData = false;
        private int shouldSendCount = 0;
        //private List<ItemData> receivedDataList = new List<ItemData>();

        private string currentDeivceMode = "inland";
        private string usbConnectType = "device"; //device   computer
        private string waitResponse = null;
        private string selectedDeviceType = "original"; // original 或 hardness
        
        // 滴定法硬度检测仪全局状态管理
        private DeviceStatusInfo? globalHardnessDeviceStatus = null; // 全局设备状态，初始值为null

        public MainForm()
        {
            CheckForIllegalCrossThreadCalls = false;

            InitializeComponent();

            initData();

            switchDeviceInInlandForeign(true);
            
            // 控制台输出程序启动信息
            System.Diagnostics.Debug.WriteLine("==========================================");
            System.Diagnostics.Debug.WriteLine("水质上报系统 - 串口通信调试模式已启动");
            System.Diagnostics.Debug.WriteLine("==========================================");
            System.Diagnostics.Debug.WriteLine("控制台将显示以下信息：");
            System.Diagnostics.Debug.WriteLine("1. 串口发送的命令及功能描述");
            System.Diagnostics.Debug.WriteLine("2. 串口接收的原始数据及解析结果");
            System.Diagnostics.Debug.WriteLine("3. 设备状态检查过程");
            System.Diagnostics.Debug.WriteLine("4. 硬度数据解析过程");
            System.Diagnostics.Debug.WriteLine("5. 错误和异常信息");
            System.Diagnostics.Debug.WriteLine("==========================================");
            System.Diagnostics.Debug.WriteLine("");
        }


        private void initData()
        {
            restClient = new RestClient(ConfigurationManager.AppSettings["BaseURL"]);
            deviceData.Items = new List<ItemData>();

            initGridControl();
        }

        private void initGridControl()
        {
            // 创建 DataGridView 列
            DataGridViewTextBoxColumn column0 = new DataGridViewTextBoxColumn();
            column0.HeaderText = "设备ID";
            column0.Name = "DeviceID";
            column0.Visible = false;

            DataGridViewTextBoxColumn column1 = new DataGridViewTextBoxColumn();
            column1.HeaderText = "序号";
            column1.Name = "No";

            DataGridViewTextBoxColumn column2 = new DataGridViewTextBoxColumn();
            column2.HeaderText = "测试项目";
            column2.Name = "TestItem";

            DataGridViewTextBoxColumn column3 = new DataGridViewTextBoxColumn();
            column3.HeaderText = "单位";
            column3.Name = "Unit";

            DataGridViewTextBoxColumn column4 = new DataGridViewTextBoxColumn();
            column4.HeaderText = "浓度";
            column4.Name = "Concentration";

            DataGridViewTextBoxColumn column5 = new DataGridViewTextBoxColumn();
            column5.HeaderText = "吸光";
            column5.Name = "Absorbancy";

            DataGridViewTextBoxColumn column6 = new DataGridViewTextBoxColumn();
            column6.HeaderText = "透光";
            column6.Name = "Transparency";

            DataGridViewTextBoxColumn column7 = new DataGridViewTextBoxColumn();
            column7.HeaderText = "测试日期";
            column7.Name = "TestDate";

            DataGridViewTextBoxColumn column8 = new DataGridViewTextBoxColumn();
            column8.HeaderText = "测试时间";
            column8.Name = "TestTime";

            // 将列添加到 DataGridView
            dataGridView1.Columns.AddRange(new DataGridViewColumn[] { column0, column1, column2, column3, column4, column5, column6, column7, column8 });

        }
        public static string[] ColumnNames = new string[] { "DeviceID", "No", "TestItem", "Unit", "Concentration", "Absorbancy",
            "Transparency","TestDate","TestTime"};

        private void showDataToList(DeviceData deviceData, bool appendData)
        {
            if (!appendData)
            {
                dataGridView1.Rows.Clear();
            }

            for (int i = 0; i < deviceData.Items.Count; i++)
            {
                // 模拟添加数据行
                DataGridViewRow row1 = new DataGridViewRow();
                row1.Cells.AddRange(new DataGridViewCell[] { new DataGridViewTextBoxCell() { Value = deviceData.Items[i].DeviceID },
                    new DataGridViewTextBoxCell() { Value = deviceData.Items[i].NO },
                    new DataGridViewTextBoxCell() { Value = deviceData.Items[i].Name },
                    new DataGridViewTextBoxCell() { Value = deviceData.Items[i].Unit },
                    new DataGridViewTextBoxCell() { Value = deviceData.Items[i].Concentration },
                    new DataGridViewTextBoxCell() { Value = deviceData.Items[i].Absorbancy },
                    new DataGridViewTextBoxCell() { Value = deviceData.Items[i].Transparency },
                    new DataGridViewTextBoxCell() { Value = deviceData.Items[i].TestDate.ToString("yyyy-MM-dd") },
                    new DataGridViewTextBoxCell() { Value = deviceData.Items[i].TestDate.ToString("HH:mm:ss") } });

                dataGridView1.Rows.Add(row1);
            }

        }

        private void btLoadFromFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.CheckFileExists = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string fileToImport = ofd.FileName;

                StreamReader streamReader = new StreamReader(fileToImport);
                string content = streamReader.ReadToEnd();
                string[] lines = content.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                string captionLine = lines[0].Replace("\r", "").Trim();
                string[] captionFields = captionLine.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);

                dataGridView1.Rows.Clear();
                dataGridView1.Columns.Clear();

                for (int i = 0; i < captionLine.Length; i++)
                {
                    DataGridViewColumn column = new DataGridViewColumn();
                    column.HeaderText = captionLine[i].ToString();
                    dataGridView1.Columns.Add(column);
                }

                for (int i = 1; i < lines.Length; i++)
                {
                    string[] dataParts = lines[i].Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
                    DataGridViewRow row = new DataGridViewRow();

                    for (int j = 0; j < dataParts.Length; j++)
                    {
                        DataGridViewCell cell = new DataGridViewTextBoxCell();
                        cell.Value = dataParts[j];
                        row.Cells.Add(cell);
                    }

                    dataGridView1.Rows.Add(row);
                }
            }
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            btReport.Enabled = (dataGridView1.SelectedRows.Count > 0);
        }

        private void btReport_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show(this, "您没有选择任何一条要上报的记录！");
                return;
            }

            //验证是否为同一指标
            string itemName = null;
            for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
            {
                if (itemName == null)
                {
                    itemName = dataGridView1.SelectedRows[i].Cells["TestItem"].Value.ToString();
                }
                else
                {
                    if (itemName.Equals(dataGridView1.SelectedRows[i].Cells["TestItem"].Value.ToString()) == false)
                    {
                        MessageBox.Show(this, "选中样本不属于同一个指标，不同取均值上报。");
                        return;
                    }
                }
            }

            //如果是浊度，必须选择个才能上报。上传时数值=过滤前平均值-过滤后平均值
            //过滤前的2次先测试，过滤后的2次后测试，一次选4个测试结果


            bool isTurbidity = dataGridView1.SelectedRows[0].Cells["TestItem"].Value.ToString().Contains("浊度");  //是否为浊度检测项

            if (isTurbidity && (dataGridView1.SelectedRows.Count != 4 && dataGridView1.SelectedRows.Count != 2 && dataGridView1.SelectedRows.Count != 1))
            {
                MessageBox.Show(this, "浊度样本必须选中1,2,或4项才能上报。");
                return;
            }

            if (!isTurbidity && (dataGridView1.SelectedRows.Count != 2 && dataGridView1.SelectedRows.Count != 1))
            {
                MessageBox.Show(this, "非浊度样本必须选中1,2项才能上报。");
                return;
            }

            Double valueConcentrationAmount = 0d;
            Double valueAbsorbancyAmount = 0d;
            Double valueTransparentAmount = 0d;

            if (isTurbidity)
            {
                if (dataGridView1.SelectedRows.Count == 1)
                {
                    valueConcentrationAmount = Double.Parse(dataGridView1.SelectedRows[0].Cells["Concentration"].Value.ToString());

                    valueAbsorbancyAmount = Double.Parse(dataGridView1.SelectedRows[0].Cells["Absorbancy"].Value.ToString());

                    valueTransparentAmount = Double.Parse(dataGridView1.SelectedRows[0].Cells["Transparency"].Value.ToString());
                }
                else if (dataGridView1.SelectedRows.Count == 2)
                {
                    valueConcentrationAmount = (Double.Parse(dataGridView1.SelectedRows[0].Cells["Concentration"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[1].Cells["Concentration"].Value.ToString())) / 2;

                    valueAbsorbancyAmount = (Double.Parse(dataGridView1.SelectedRows[0].Cells["Absorbancy"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[1].Cells["Absorbancy"].Value.ToString())) / 2;

                    valueTransparentAmount = (Double.Parse(dataGridView1.SelectedRows[0].Cells["Transparency"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[1].Cells["Transparency"].Value.ToString())) / 2;
                }
                else if (dataGridView1.SelectedRows.Count == 4)
                {
                    valueConcentrationAmount = (Double.Parse(dataGridView1.SelectedRows[0].Cells["Concentration"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[1].Cells["Concentration"].Value.ToString())) / 2
                         - (Double.Parse(dataGridView1.SelectedRows[2].Cells["Concentration"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[3].Cells["Concentration"].Value.ToString())) / 2;

                    valueAbsorbancyAmount = (Double.Parse(dataGridView1.SelectedRows[0].Cells["Absorbancy"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[1].Cells["Absorbancy"].Value.ToString())) / 2
                         - (Double.Parse(dataGridView1.SelectedRows[2].Cells["Absorbancy"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[3].Cells["Absorbancy"].Value.ToString())) / 2;

                    valueTransparentAmount = (Double.Parse(dataGridView1.SelectedRows[0].Cells["Transparency"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[1].Cells["Transparency"].Value.ToString())) / 2
                         - (Double.Parse(dataGridView1.SelectedRows[2].Cells["Transparency"].Value.ToString()) + Double.Parse(dataGridView1.SelectedRows[3].Cells["Transparency"].Value.ToString())) / 2;
                }
            }
            else
            {
                for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                {
                    valueConcentrationAmount += Double.Parse(dataGridView1.SelectedRows[i].Cells["Concentration"].Value.ToString());
                    valueAbsorbancyAmount += Double.Parse(dataGridView1.SelectedRows[i].Cells["Absorbancy"].Value.ToString());
                    valueTransparentAmount += Double.Parse(dataGridView1.SelectedRows[i].Cells["Transparency"].Value.ToString());
                }

                valueConcentrationAmount = valueConcentrationAmount / dataGridView1.SelectedRows.Count;
                valueAbsorbancyAmount = valueAbsorbancyAmount / dataGridView1.SelectedRows.Count;
                valueTransparentAmount = valueTransparentAmount / dataGridView1.SelectedRows.Count;
            }

            ItemData itemData = new ItemData();
            itemData.Unit = dataGridView1.SelectedRows[0].Cells["Unit"].Value.ToString();

            

            itemData.TestDate = DateTime.Parse(dataGridView1.SelectedRows[0].Cells["TestDate"].Value.ToString());
            itemData.DeviceID = dataGridView1.SelectedRows[0].Cells["DeviceID"].Value.ToString();
            itemData.NO = dataGridView1.SelectedRows[0].Cells["No"].Value.ToString();
            itemData.Name = dataGridView1.SelectedRows[0].Cells["TestItem"].Value.ToString();
            if (itemData.Name.Contains("硬度"))
            {
                itemData.Concentration = Tools.RoundToEven(valueConcentrationAmount * 0.4, 3).ToString("#00000.000");
                itemData.Absorbancy = Tools.RoundToEven(valueAbsorbancyAmount * 0.4, 3).ToString("#00000.00");
                itemData.Transparency = Tools.RoundToEven(valueTransparentAmount * 0.4, 3).ToString("#00000.00");
            }
            else
            {
                itemData.Concentration = Tools.RoundToEven(valueConcentrationAmount, 3).ToString("#00000.000");
                itemData.Absorbancy = Tools.RoundToEven(valueAbsorbancyAmount, 3).ToString("#00000.00");
                itemData.Transparency = Tools.RoundToEven(valueTransparentAmount, 3).ToString("#00000.00");
            }

            ReportConfirmDialog confirmDialog = new ReportConfirmDialog(itemData);
            if (confirmDialog.ShowDialog() == DialogResult.OK)
            {
                Double score = confirmDialog.Score;

                string token = null;
                try
                {
                    token = getToken();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "上报失败，获取Token失败，原因：" + ex.Message);
                    return;
                }

                //调用Restful api上报数据
                ReportData reportData = new ReportData();
                string url = null;

                reportData.Score = score.ToString("#00000.00");
                reportData.Id = itemData.DeviceID;

                string apiAddress = ConfigurationManager.AppSettings["ApiAddress"];
                if (itemData.Name.ToLower().IndexOf("ph") >= 0)
                {
                    url = apiAddress + "/saveResultPH";
                }
                else if (itemData.Name.ToLower().Equals("hardness") || itemData.Name.IndexOf("硬度") >= 0)
                {
                    url = apiAddress + "/saveResultHardness";
                }
                else if (itemData.Name.ToLower().Equals("turbidity") || itemData.Name.IndexOf("浊度") >= 0)
                {
                    url = apiAddress + "/saveResultTurbidity";
                }
                else if (itemData.Name.ToLower().Equals("conductivity") || itemData.Name.IndexOf("电导率") >= 0)
                {
                    url = apiAddress + "/saveResultConductivity";
                }
                else if (itemData.Name.ToLower().Equals("fe") || itemData.Name.IndexOf("铁") >= 0)
                {
                    url = apiAddress + "/saveResultFe";
                }
                else if (itemData.Name.IndexOf("细菌") >= 0)
                {
                    MessageBox.Show(this, "未实现细菌数据的上报。");
                    return;
                }
                else
                {
                    return;
                }

                try
                {
                    string body = Newtonsoft.Json.JsonConvert.SerializeObject(reportData);
                    Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
                    keyValuePairs.Add("token", token);

                    string response = restClient.Post(body, url, keyValuePairs);

                    if (response != null && response.Equals("未知原因"))
                    {
                        MessageBox.Show(this, "数据上传失败，" + response);
                    }
                    else
                    {
                        //解析结果
                        ResponseDto responseDto = (ResponseDto)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(ResponseDto));
                        if (responseDto != null)
                        {
                            if (responseDto.code == 200)
                            {
                                MessageBox.Show(this, "数据上报成功");
                            }
                            else
                            {
                                MessageBox.Show(this, "数据上报失败，原因：" + responseDto.msg);
                            }
                        }
                        else
                        {
                            MessageBox.Show(this, "解析响应数据失败！");
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "数据上报失败，原图：" + ex.Message);
                }
            }
        }


        private void btReadData_Click(object sender, EventArgs e)
        {
            if (currentDeivceMode.Trim().Equals("inland") && btReadData.Text.Equals("从串口读取数据"))
            {
                try
                {
                    if (txtDeviceID.Text.Equals(""))
                    {
                        MessageBox.Show(this, "请先扫描设备ID");
                        return;
                    }

                    // 显示设备选择弹窗
                    DeviceSelectionDialog deviceDialog = new DeviceSelectionDialog();
                    if (deviceDialog.ShowDialog() == DialogResult.OK)
                    {
                        selectedDeviceType = deviceDialog.SelectedDeviceType;
                        
                        // 重置全局设备状态变量
                        globalHardnessDeviceStatus = null;
                        
                        // 重置等待响应标志
                        waitResponse = null;
                    }
                    else
                    {
                        return; // 用户取消选择
                    }

                    bool initResult = initSerialPort();

                    if (!initResult)
                    {
                        return;
                    }

                    deviceData.DeviceID = txtDeviceID.Text.Trim();
                    deviceData.Items.Clear();

                    sendReadCommand();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("报错位置3：" + ex.Message);
                }
            }
            else if (currentDeivceMode.Trim().Equals("foreign") && btReadData.Text.Equals("从U盘读取数据"))
            {
                deviceData.DeviceID = txtDeviceID.Text.Trim();
                deviceData.Items.Clear();

                //读取U盘数据
                List<string> readSuccessFileList = readDataFromUDisk();

                if (deviceData.Items.Count > 0)
                {
                    showDataToList(deviceData, true);
                }

                if (readSuccessFileList != null && readSuccessFileList.Count > 0)
                {
                    //已读取成功的文件。
                    string udiskPath = ConfigurationManager.AppSettings["UDiskPath"] == null ? "" : ConfigurationManager.AppSettings["UDiskPath"].Trim();
                    if (udiskPath == null || udiskPath.Length == 0)
                    {
                        MessageBox.Show(this, "未设置U盘路径！");
                        return;
                    }
                    else
                    {
                        if (Directory.Exists(udiskPath))
                        {
                            //if (MessageBox.Show(this, "是否要清除U盘中的数据文件？", "文件清理确认", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                            //{
                            //    if (!Directory.Exists(udiskPath))
                            //    {
                            //        MessageBox.Show(this, "设置的U盘路径不存在");
                            //        return;
                            //    }
                            //    else
                            //    {
                            var csvFiles = new DirectoryInfo(udiskPath)
                                .GetFiles("*.csv") // Get all CSV files
                                .OrderBy(file => file.CreationTime) // Sort by creation time
                                .ToArray(); // Convert to array if needed

                            if (csvFiles.Length == 0)
                            {
                                return;
                            }

                            for (int i = 0; i < csvFiles.Length; i++)
                            {
                                string fileName = csvFiles[i].Name;
                                try
                                {
                                    File.Delete(fileName);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(this, ex.Message);
                                }
                            }
                            //}
                            //}
                        }
                    }

                }
            }
            else
            {
                MessageBox.Show(this, "未知的检测设备模式：" + (currentDeivceMode.Trim().Equals("inland") ? "国内检测设备" : (currentDeivceMode.Trim().Equals("foreign") ? "国外检测设备" : "未知设备类型")));
            }
        }

        private bool initSerialPort()
        {
            try
            {
                if (serialPort == null)
                {
                    serialPort = new SerialPort();
                    serialPort.BaudRate = Int32.Parse(ConfigurationManager.AppSettings["BaudRate"]);
                    serialPort.PortName = ConfigurationManager.AppSettings["COMPort"];

                    // 设置奇偶校验
                    string verifyMode = ConfigurationManager.AppSettings["VerifyBits"].ToLower();
                    switch (verifyMode)
                    {
                        case "none":
                            serialPort.Parity = Parity.None;
                            break;
                        case "odd":
                            serialPort.Parity = Parity.Odd;
                            break;
                        case "even":
                            serialPort.Parity = Parity.Even;
                            break;
                        case "mark":
                            serialPort.Parity = Parity.Mark;
                            break;
                        case "space":
                            serialPort.Parity = Parity.Space;
                            break;
                        default:
                            serialPort.Parity = Parity.None;
                            break;
                    }
                    // 设置数据位数
                    serialPort.DataBits = Int32.Parse(ConfigurationManager.AppSettings["DataBits"].ToString());
                    string stopBits = ConfigurationManager.AppSettings["StopBits"].ToLower();
                    switch (stopBits)
                    {
                        case "none":
                            serialPort.StopBits = StopBits.None;
                            break;
                        case "one":
                            serialPort.StopBits = StopBits.One;
                            break;
                        case "onepointfive":
                            serialPort.StopBits = StopBits.OnePointFive;
                            break;
                        case "two":
                            serialPort.StopBits = StopBits.Two;
                            break;
                        default:
                            serialPort.StopBits = StopBits.None;
                            break;
                    }

                    // 设置握手协议
                    string handshake = ConfigurationManager.AppSettings["Handshake"].ToLower();
                    switch (handshake)
                    {
                        case "none":
                            serialPort.Handshake = Handshake.None;
                            break;

                        case "requesttosendxonxoff":
                            serialPort.Handshake = Handshake.RequestToSendXOnXOff;
                            break;

                        case "xonxoff":
                            serialPort.Handshake = Handshake.XOnXOff;
                            break;

                        case "requesttosend":
                            serialPort.Handshake = Handshake.RequestToSend;
                            break;
                        default:
                            serialPort.Handshake = Handshake.None;
                            break;
                    }


                    serialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler); // 接收到数据时的事件
                    serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); // 接收到数据时的事件
                    serialPort.Open();
                }
                else
                {
                    if (serialPort.IsOpen == false)
                    {
                        serialPort.Open();
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("报错位置4：" + ex.Message);

                releaseSerialPort();

                return false;
            }
        }

        private void releaseSerialPort()
        {
            if (serialPort != null)
            {
                try
                {
                    serialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler);
                    serialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler);
                    serialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler);

                    if (serialPort.IsOpen)
                    {
                        try
                        {
                            serialPort.Close();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("报错位置5：" + ex.Message);
                        }
                    }

                    serialPort.Dispose();
                    serialPort = null;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("报错位置6：" + ex.Message);
                    return;
                }
            }
        }
        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {

            SerialPort sp = (SerialPort)sender;

            if (currentDeivceMode.Equals("inland"))
            {
                try
                {
                    //string indata = sp.ReadExisting();
                    byte[] datas = new byte[sp.BytesToRead];
                    sp.Read(datas, 0, datas.Length);
                    
                    // 控制台输出接收到的原始数据
                    System.Diagnostics.Debug.WriteLine("=== 串口接收数据 ===");
                    System.Diagnostics.Debug.WriteLine($"接收时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                    System.Diagnostics.Debug.WriteLine($"数据长度: {datas.Length} 字节");
                    System.Diagnostics.Debug.WriteLine($"原始数据: {BitConverter.ToString(datas).Replace("-", " ")}");
                    System.Diagnostics.Debug.WriteLine($"十六进制: {BitConverter.ToString(datas).Replace("-", "")}");
                    System.Diagnostics.Debug.WriteLine("==================");

                    int buffersStartLength_error1 = buffers.Length;
                    int datasLength_error1 = datas.Length;

                    try
                    {
                        //将结果接到内容缓存中
                        Array.Resize(ref buffers, buffers.Length + datas.Length);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("扩容错误：" + buffersStartLength_error1 + "," + datasLength_error1 + "," + buffers.Length);
                    }

                    int datasLength_error2 = datas.Length;
                    int buffersLength_error2 = buffers.Length;
                    int position_error2 = buffers.Length - datas.Length;
                    try
                    {
                        Buffer.BlockCopy(datas, 0, buffers, buffers.Length - datas.Length, datas.Length);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("追加错误：" + buffersLength_error2 + "," + datasLength_error2 + "," + position_error2);
                    }

                    if (selectedDeviceType == "original")
                    {
                        // 原检测设备的数据处理
                        if (isPackageCompleted(buffers))
                        {
                            //tmrReadDelay.Enabled = false;
                            operateReceiveData(buffers, false);
                            LogForm.getInstance().showLog("已处理数据");
                        }
                        else
                        {
                            LogForm.getInstance().showLog("数据不完整");
                        }
                    }
                    else if (selectedDeviceType == "hardness")
                    {
                        // 滴定试剂法硬度检测仪的数据处理
                        if (ModBusRTUHelper.IsValidModBusResponse(buffers))
                        {
                            // 根据等待响应类型处理数据
                            if (waitResponse == "device_status")
                            {
                                handleDeviceStatusResponse(buffers);
                                LogForm.getInstance().showLog("已处理设备状态数据");
                            }
                            else if (waitResponse == "hardness_data")
                            {
                                // 根据配置决定是否检查全局设备状态
                                string checkStatusConfig = ConfigurationManager.AppSettings["CheckHardnessDeviceStatus"];
                                bool shouldCheckStatus = true; // 默认检查状态
                                
                                if (!string.IsNullOrEmpty(checkStatusConfig))
                                {
                                    bool.TryParse(checkStatusConfig, out shouldCheckStatus);
                                }
                                
                                if (shouldCheckStatus)
                                {
                                    // 检查全局设备状态，只有在"等待"状态时才处理硬度数据
                                    if (globalHardnessDeviceStatus != null && 
                                        globalHardnessDeviceStatus.IsValid && 
                                        globalHardnessDeviceStatus.OperatingStatus == 0)
                                    {
                                        operateReceiveHardnessData(buffers, false);
                                        LogForm.getInstance().showLog("已处理硬度数据");
                                    }
                                    else
                                    {
                                        System.Diagnostics.Debug.WriteLine("硬度数据被忽略:");
                                        System.Diagnostics.Debug.WriteLine($"  原因: 设备状态不是'等待'");
                                        System.Diagnostics.Debug.WriteLine($"  当前状态: {globalHardnessDeviceStatus?.OperatingStatus ?? -1}");
                                        System.Diagnostics.Debug.WriteLine($"  状态有效: {globalHardnessDeviceStatus?.IsValid ?? false}");
                                        System.Diagnostics.Debug.WriteLine("==================");
                                        
                                        LogForm.getInstance().showLog("设备状态不是'等待'，忽略硬度数据");
                                    }
                                }
                                else
                                {
                                    // 不检查设备状态，直接处理硬度数据
                                    operateReceiveHardnessData(buffers, false);
                                    LogForm.getInstance().showLog("已处理硬度数据（跳过状态检查）");
                                }
                            }
                            else
                            {
                                // 默认处理为硬度数据（兼容旧逻辑）
                                // 根据配置决定是否检查全局设备状态
                                string checkStatusConfig = ConfigurationManager.AppSettings["CheckHardnessDeviceStatus"];
                                bool shouldCheckStatus = true; // 默认检查状态
                                
                                if (!string.IsNullOrEmpty(checkStatusConfig))
                                {
                                    bool.TryParse(checkStatusConfig, out shouldCheckStatus);
                                }
                                
                                if (shouldCheckStatus)
                                {
                                    // 检查全局设备状态
                                    if (globalHardnessDeviceStatus != null && 
                                        globalHardnessDeviceStatus.IsValid && 
                                        globalHardnessDeviceStatus.OperatingStatus == 0)
                                    {
                                        operateReceiveHardnessData(buffers, false);
                                        LogForm.getInstance().showLog("已处理硬度数据");
                                    }
                                    else
                                    {
                                        System.Diagnostics.Debug.WriteLine("硬度数据被忽略:");
                                        System.Diagnostics.Debug.WriteLine($"  原因: 设备状态不是'等待'");
                                        System.Diagnostics.Debug.WriteLine($"  当前状态: {globalHardnessDeviceStatus?.OperatingStatus ?? -1}");
                                        System.Diagnostics.Debug.WriteLine($"  状态有效: {globalHardnessDeviceStatus?.IsValid ?? false}");
                                        System.Diagnostics.Debug.WriteLine("==================");
                                        
                                        LogForm.getInstance().showLog("设备状态不是'等待'，忽略硬度数据");
                                    }
                                }
                                else
                                {
                                    // 不检查设备状态，直接处理硬度数据
                                    operateReceiveHardnessData(buffers, false);
                                    LogForm.getInstance().showLog("已处理硬度数据（跳过状态检查）");
                                }
                            }
                        }
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("ModBus数据验证失败:");
                            System.Diagnostics.Debug.WriteLine($"  数据长度: {buffers.Length} 字节");
                            System.Diagnostics.Debug.WriteLine($"  原始数据: {BitConverter.ToString(buffers).Replace("-", " ")}");
                            System.Diagnostics.Debug.WriteLine($"  验证结果: 数据不完整或无效");
                            System.Diagnostics.Debug.WriteLine("==================");
                            
                            LogForm.getInstance().showLog("ModBus数据不完整或无效");
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("串口数据接收异常:");
                    System.Diagnostics.Debug.WriteLine($"  异常信息: {ex.Message}");
                    System.Diagnostics.Debug.WriteLine($"  异常类型: {ex.GetType().Name}");
                    System.Diagnostics.Debug.WriteLine($"  堆栈跟踪: {ex.StackTrace}");
                    System.Diagnostics.Debug.WriteLine("==================");
                    
                    MessageBox.Show("报错位置1：" + ex.Message);
                }
            }
            else if (currentDeivceMode.Equals("foreign"))
            {
                //string indata = sp.ReadExisting();
                byte[] datas = new byte[sp.BytesToRead];
                sp.Read(datas, 0, datas.Length);

                if (datas.Length > 0)
                {
                    string resultString = Encoding.UTF8.GetString(datas);

                    if (resultString.Equals(waitResponse))
                    {
                        UsbStates usbStates = (UsbStates)Newtonsoft.Json.JsonConvert.DeserializeObject(resultString, typeof(UsbStates));
                        if (usbStates.states == 0) //usb连接设备
                        {

                            usbConnectType = "device";
                            btUSBConnectDevice.ForeColor = System.Drawing.Color.Green;
                            btUSBConnectComputer.ForeColor = System.Drawing.Color.Black;

                            btReadData.Enabled = false;
                            grpOperationArea.Enabled = true;
                        }
                        else if (usbStates.states == 1) //usb连接电脑
                        {

                            usbConnectType = "computer";
                            btUSBConnectDevice.ForeColor = System.Drawing.Color.Black;
                            btUSBConnectComputer.ForeColor = System.Drawing.Color.Green;

                            btReadData.Enabled = true;
                            grpOperationArea.Enabled = true;
                        }
                        else
                        {
                            grpOperationArea.Enabled = false;
                            MessageBox.Show(this, "未知USB连接状态：" + usbStates.states.ToString());
                            return;
                        }
                    }
                }
            }
        }


        private void operateReceiveData(byte[] buffers, bool appendData)
        {
            try
            {
                
                if (isPackageCompleted(buffers))
                {
                    uint recordCount = Tools.ByteToUInt32(buffers, 1, true);//先低后高

                    if (recordCount > 0)
                    {
                        if (deviceData.Items != null)
                        {
                            deviceData.Items.Clear();
                        }

                        //读取指定个数的值
                        for (int i = 0; i < recordCount; i++)
                        {
                            ushort testItemNo = Tools.ByteToUInt16(buffers, i * 23 + 5, true); //先低后高
                            byte unitNo = buffers[i * 23 + 7];
                            Single concentration = Tools.ByteToSingle(buffers, i * 23 + 8, true);//先高后低
                            Single absorbancy = Tools.ByteToSingle(buffers, i * 23 + 12, true);
                            Single transparency = Tools.ByteToSingle(buffers, i * 23 + 16, true);
                            byte year = buffers[i * 23 + 20];
                            byte month = buffers[i * 23 + 21];
                            byte date = buffers[i * 23 + 22];
                            byte hour = buffers[i * 23 + 23];
                            byte minute = buffers[i * 23 + 24];
                            byte seconds = buffers[i * 23 + 25];
                            byte userNo = buffers[i * 23 + 26];
                            byte reserve = buffers[i * 23 + 27];

                            ItemData item = new ItemData();
                            item.DeviceID = txtDeviceID.Text;
                            if (testItemNo - 1 > Constants.TestNames.Length - 1)
                            {
                                item.Name = "PH";
                            }
                            else
                            {
                                item.Name = Constants.TestNames[testItemNo - 1];
                            }

                            if (unitNo > Constants.UnitsDict.Count - 1)
                            {
                                item.Unit = "";
                            }
                            else
                            {
                                item.Unit = Constants.UnitsDict[unitNo];
                            }

                            item.Concentration = Tools.RoundToEven(concentration, 3).ToString("00000.000");
                            item.Absorbancy = Tools.RoundToEven(absorbancy, 3).ToString("0.0000");
                            item.Transparency = Tools.RoundToEven(transparency, 3).ToString("0.0000");
                            item.TestDate = DateTime.Parse("20" + year.ToString("D2") + "-" + month.ToString("D2") + "-" + date.ToString("D2") + " " + hour.ToString("D2") +
                                ":" + minute.ToString("D2") + ":" + seconds.ToString("D2"));
                            item.UserNo = userNo.ToString("D2");
                            item.NO = (i + 1) + "";

                            deviceData.Items.Add(item);

                            byte[] originalData = new byte[23];
                            Buffer.BlockCopy(buffers, i * 23 + 5, originalData, 0, 23);
                            item.hexDatas = Tools.ByteArrayToHexString(originalData);

                            ExcelHelper.AppendDataToCsv(Tools.getSavePath() + "\\data_history.csv".Replace("\\\\", "\\"), item);

                        }
                    }

                    if (deviceData.Items.Count > 0)
                    {
                        showDataToList(deviceData, appendData);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("解析数据失败：" + ex.Message + Tools.ByteArrayToHexString(buffers));

                return;
            }
        }

        /// <summary>
        /// 处理硬度检测仪返回的数据
        /// </summary>
        /// <param name="responseData">设备返回的原始数据</param>
        /// <param name="appendData">是否追加数据</param>
        private void operateReceiveHardnessData(byte[] responseData, bool appendData)
        {
            try
            {
                // 控制台输出硬度数据响应
                System.Diagnostics.Debug.WriteLine("=== 硬度数据响应 ===");
                System.Diagnostics.Debug.WriteLine($"响应时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                System.Diagnostics.Debug.WriteLine($"数据长度: {responseData.Length} 字节");
                System.Diagnostics.Debug.WriteLine($"原始数据: {BitConverter.ToString(responseData).Replace("-", " ")}");
                System.Diagnostics.Debug.WriteLine($"十六进制: {BitConverter.ToString(responseData).Replace("-", "")}");
                System.Diagnostics.Debug.WriteLine("==================");
                
                // 解析硬度值
                float? hardnessValue = ModBusRTUHelper.ParseHardnessResponse(responseData);
                
                if (hardnessValue.HasValue)
                {
                    System.Diagnostics.Debug.WriteLine("硬度数据解析结果:");
                    System.Diagnostics.Debug.WriteLine($"  硬度值: {hardnessValue.Value:F4} mg/L");
                    System.Diagnostics.Debug.WriteLine($"  解析成功: 是");
                    System.Diagnostics.Debug.WriteLine("==================");
                    if (deviceData.Items != null && !appendData)
                    {
                        deviceData.Items.Clear();
                    }

                    // 创建硬度数据项
                    ItemData item = new ItemData();
                    item.DeviceID = txtDeviceID.Text;
                    item.Name = "硬度";
                    item.Unit = "mg/L"; // 根据实际单位调整
                    item.Concentration = Tools.RoundToEven(hardnessValue.Value, 4).ToString("00000.000");
                    item.Absorbancy = "0.0000"; // 硬度检测仪可能没有吸光度数据
                    item.Transparency = "0.0000"; // 硬度检测仪可能没有透明度数据
                    item.TestDate = DateTime.Now;
                    item.UserNo = "01";
                    item.NO = (deviceData.Items.Count + 1).ToString();

                    // 将原始数据转换为十六进制字符串
                    item.hexDatas = Tools.ByteArrayToHexString(responseData);

                    deviceData.Items.Add(item);

                    // 保存到CSV文件
                    ExcelHelper.AppendDataToCsv(Tools.getSavePath() + "\\data_history.csv".Replace("\\\\", "\\"), item);

                    // 显示数据
                    if (deviceData.Items.Count > 0)
                    {
                        showDataToList(deviceData, appendData);
                    }

                    MessageBox.Show(this, $"硬度检测成功！\n硬度值：{hardnessValue.Value:F4} mg/L");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("硬度数据解析结果:");
                    System.Diagnostics.Debug.WriteLine($"  解析成功: 否");
                    System.Diagnostics.Debug.WriteLine($"  失败原因: 数据格式错误或校验失败");
                    System.Diagnostics.Debug.WriteLine($"  原始数据: {Tools.ByteArrayToHexString(responseData)}");
                    System.Diagnostics.Debug.WriteLine("==================");
                    
                    MessageBox.Show(this, "解析硬度数据失败！\n原始数据：" + Tools.ByteArrayToHexString(responseData));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("硬度数据处理异常:");
                System.Diagnostics.Debug.WriteLine($"  异常信息: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"  异常类型: {ex.GetType().Name}");
                System.Diagnostics.Debug.WriteLine("==================");
                
                MessageBox.Show(this, "处理硬度数据时发生错误：" + ex.Message);
            }
        }

        private void operateReceiveData(string indata, bool appendData)
        {
            //解析数据
            byte[] buffers = Tools.hexStringToByteArray(indata);
            operateReceiveData(buffers, appendData);
        }

        private void btScan_Click(object sender, EventArgs e)
        {
            if (btScan.Text.Equals("开始扫码"))
            {
                //清除表格内容
                btReadData.Enabled = false;
                dataGridView1.Rows.Clear();
                btScan.Text = "停止扫码";

                txtDeviceID.Text = "";
                txtDeviceID.Enabled = true;
                btReadData.Enabled = false;
                //btInputManual.Enabled = false;

                txtDeviceID.Focus();
            }
            else if (btScan.Text.Equals("停止扫码"))
            {
                btScan.Text = "开始扫码";
                txtDeviceID.Enabled = false;
                btReadData.Enabled = true;
                //btInputManual.Enabled = true;
                btReadData.Focus();
            }
        }

        private void btSaveToFile_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "所有文件|*.*|文本文件|(*.txt)";
            saveFileDialog.CheckFileExists = false;
            saveFileDialog.CheckPathExists = true;

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string saveFilePath = saveFileDialog.FileName;

                StreamWriter streamWriter = new StreamWriter(saveFilePath);
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    if (j == 0)
                    {
                        streamWriter.Write(dataGridView1.Columns[j].HeaderText);
                    }
                    else
                    {
                        streamWriter.Write("\t" + dataGridView1.Columns[j].HeaderText);
                    }
                }

                streamWriter.WriteLine();

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        if (j == 0)
                        {
                            streamWriter.Write(dataGridView1.Rows[i].Cells[j].Value.ToString());
                        }
                        else
                        {
                            streamWriter.Write("\t" + dataGridView1.Rows[i].Cells[j].Value.ToString());
                        }
                    }

                    streamWriter.WriteLine();
                }

                streamWriter.Flush();
                streamWriter.Close();
            }
        }


        private void beOpenLocalDir_Click(object sender, EventArgs e)
        {

            // 替换为你要打开的本地目录路径
            string directoryPath = Tools.getSavePath();

            // 打开目录
            Process.Start("explorer.exe", directoryPath);
        }

        private void menuItemFillTestData2_Click(object sender, EventArgs e)
        {
            string indata = "55 01 00 00 00 41 00 06 40 BB E4 8D 00 00 00 00 00 00 00 00 18 09 05 0F 0C 27 01 00 1D 03";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        private void menuItemFillTestData3_Click(object sender, EventArgs e)
        {
            string indata = "55 02 00 00 00 41 00 06 40 BB E4 8D 00 00 00 00 00 00 00 00 18 09 05 0F 0C 27 01 00" +
                                          " 41 00 06 40 BC 2A CE 00 00 00 00 00 00 00 00 18 09 05 0F 0D 3A 01 00 D6 05";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        private void menuItemFillTestData4_Click(object sender, EventArgs e)
        {
            string indata = "55 01 00 00 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 09 05 0F 10 1C 01 00 6D 00";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        private void menuItemFillTestData5_Click(object sender, EventArgs e)
        {
            string indata = "55 01 00 00 00 2D 00 04 42 3A 03 82 00 00 00 00 00 00 00 00 18 09 05 0F 12 07 01 00 82 01";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        private void menuItemFillTestData6_Click(object sender, EventArgs e)
        {
            string indata = "55 01 00 00 00 3B 00 08 3E 62 18 21 00 00 00 00 00 00 00 00 18 09 05 0F 13 14 01 00 7A 01";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        private void 填充测试数据7ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string indata = "55 01 00 00 00 1C 00 01 39 DE D4 7C 00 00 00 00 00 00 00 00 18 09 05 0F 14 0B 01 00 DA 02";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        private void 填充测试数据8ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string indata = "55 01 00 00 00 1C 00 01 39 DE D4 7C 00 00 00 00 00 00 00 00 18 09 05 0F 14 0B 01 00 DA 02";
            operateReceiveData(indata.Replace(" ", ""), true);
        }


        private void menuItemInputManual_Click(object sender, EventArgs e)
        {
            InputManualDialog inputManualDialog = new InputManualDialog();
            if (inputManualDialog.ShowDialog() == DialogResult.OK)
            {
                operateReceiveData(inputManualDialog.InputData.ToUpper().Replace(" ", ""), inputManualDialog.AppendData);
            }
        }


        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                releaseSerialPort();
            }
            catch (Exception ex)
            {

            }
        }

        private void btInputManual_Click(object sender, EventArgs e)
        {
            if (txtDeviceID.Text.Trim().Equals(""))
            {
                MessageBox.Show(this, "请先扫码设备ID");
                return;
            }

            InputDataManualDialog dialog = new InputDataManualDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                ItemData item = dialog.ItemData;
                item.DeviceID = txtDeviceID.Text.Trim();

                if (deviceData.Items != null)
                {
                    deviceData.Items.Clear();
                }

                deviceData.Items.Add(item);
                showDataToList(deviceData, false);

                ExcelHelper.AppendDataToCsv(Tools.getSavePath() + "\\data_history_" + DateTime.Now.ToString("yyyyMMdd") + ".csv".Replace("\\\\", "\\"), item);
            }
        }

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        private string getToken()
        {

            GetTokenData getTokenData = new GetTokenData();
            string url = null;

            getTokenData.userName = "shuizhi";
            getTokenData.password = "Aa123456";

            string apiAddress = ConfigurationManager.AppSettings["ApiAddress"];

            url = apiAddress + "/getToken";
            string body = Newtonsoft.Json.JsonConvert.SerializeObject(getTokenData);

            string response = restClient.Post(body, url, null);

            ResponseDto responseDto = (ResponseDto)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(ResponseDto));
            if (responseDto != null)
            {
                if (responseDto.code == 200)
                {

                }
                else
                {
                    throw new Exception(responseDto.msg);
                }
            }
            else
            {
                throw new Exception("登录失败");
            }

            return responseDto.data;
        }

        private void 日志容器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (LogForm.getInstance().Visible == false)
            {
                LogForm.getInstance().Show();
                LogForm.getInstance().TopMost = true;
            }
        }


        private void sendReadCommand()
        {
            try
            {
                buffers = new byte[0];
                byte[] sendBuffers;
                
                if (selectedDeviceType == "original")
                {
                    // 原检测设备：发送 0xAA
                    sendBuffers = new byte[1];
                    sendBuffers[0] = 0xAA;
                    
                    // 控制台输出发送的命令
                    System.Diagnostics.Debug.WriteLine("=== 串口发送命令 ===");
                    System.Diagnostics.Debug.WriteLine($"设备类型: 多参数水质测定仪");
                    System.Diagnostics.Debug.WriteLine($"命令内容: 0x{sendBuffers[0]:X2}");
                    System.Diagnostics.Debug.WriteLine($"命令描述: 读取多参数水质测定仪数据");
                    System.Diagnostics.Debug.WriteLine($"发送时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                    System.Diagnostics.Debug.WriteLine("==================");
                }
                else if (selectedDeviceType == "hardness")
                {
                    // 滴定试剂法硬度检测仪：根据配置决定是否检查设备状态
                    string checkStatusConfig = ConfigurationManager.AppSettings["CheckHardnessDeviceStatus"];
                    bool shouldCheckStatus = true; // 默认检查状态
                    
                    if (!string.IsNullOrEmpty(checkStatusConfig))
                    {
                        bool.TryParse(checkStatusConfig, out shouldCheckStatus);
                    }
                    
                    if (shouldCheckStatus)
                    {
                        // 检查设备状态流程
                        System.Diagnostics.Debug.WriteLine("=== 串口发送命令 ===");
                        System.Diagnostics.Debug.WriteLine($"设备类型: 滴定试剂法硬度检测仪");
                        System.Diagnostics.Debug.WriteLine($"命令描述: 开始检查设备状态流程");
                        System.Diagnostics.Debug.WriteLine($"发送时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                        System.Diagnostics.Debug.WriteLine("==================");
                        
                        checkDeviceStatusAndReadHardness();
                    }
                    else
                    {
                        // 直接读取硬度数据
                        System.Diagnostics.Debug.WriteLine("=== 串口发送命令 ===");
                        System.Diagnostics.Debug.WriteLine($"设备类型: 滴定试剂法硬度检测仪");
                        System.Diagnostics.Debug.WriteLine($"命令描述: 直接读取硬度数据（跳过状态检查）");
                        System.Diagnostics.Debug.WriteLine($"发送时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                        System.Diagnostics.Debug.WriteLine("==================");
                        
                        readHardnessDataDirectly();
                    }
                    return;
                }
                else
                {
                    MessageBox.Show("未知的设备类型：" + selectedDeviceType);
                    return;
                }
                
                serialPort.Write(sendBuffers, 0, sendBuffers.Length);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"发送命令时发生错误: {ex.Message}");
                MessageBox.Show("报错位置2：" + ex.Message);
            }
        }

        /// <summary>
        /// 检查设备状态并读取硬度数据
        /// </summary>
        private void checkDeviceStatusAndReadHardness()
        {
            try
            {
                // 先发送读取设备状态的命令
                byte[] statusCommand = ModBusRTUHelper.GenerateReadDeviceStatusCommand();
                
                // 控制台输出发送的状态检查命令
                System.Diagnostics.Debug.WriteLine("=== 串口发送命令 ===");
                System.Diagnostics.Debug.WriteLine($"设备类型: 滴定试剂法硬度检测仪");
                System.Diagnostics.Debug.WriteLine($"命令类型: 读取设备状态");
                System.Diagnostics.Debug.WriteLine($"命令内容: {BitConverter.ToString(statusCommand).Replace("-", " ")}");
                System.Diagnostics.Debug.WriteLine($"命令描述: 读取设备运行状态和报警状态 (寄存器900-901)");
                System.Diagnostics.Debug.WriteLine($"ModBus格式: 设备地址=0x{statusCommand[0]:X2}, 功能码=0x{statusCommand[1]:X2}, 起始地址=0x{statusCommand[2]:X2}{statusCommand[3]:X2}, 寄存器数量={statusCommand[4] * 256 + statusCommand[5]}");
                System.Diagnostics.Debug.WriteLine($"发送时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                System.Diagnostics.Debug.WriteLine("==================");
                
                serialPort.Write(statusCommand, 0, statusCommand.Length);
                
                // 设置等待状态响应的标志
                waitResponse = "device_status";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"发送设备状态检查命令时发生错误: {ex.Message}");
                MessageBox.Show("检查设备状态时发生错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 处理设备状态响应
        /// </summary>
        /// <param name="responseData">设备返回的状态数据</param>
        private void handleDeviceStatusResponse(byte[] responseData)
        {
            try
            {
                // 控制台输出设备状态响应数据
                System.Diagnostics.Debug.WriteLine("=== 设备状态响应 ===");
                System.Diagnostics.Debug.WriteLine($"响应时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                System.Diagnostics.Debug.WriteLine($"数据长度: {responseData.Length} 字节");
                System.Diagnostics.Debug.WriteLine($"原始数据: {BitConverter.ToString(responseData).Replace("-", " ")}");
                System.Diagnostics.Debug.WriteLine($"十六进制: {BitConverter.ToString(responseData).Replace("-", "")}");
                System.Diagnostics.Debug.WriteLine("==================");
                DeviceStatusInfo statusInfo = ModBusRTUHelper.ParseDeviceStatusResponse(responseData);
                
                if (statusInfo == null || !statusInfo.IsValid)
                {
                    // 更新全局状态为无效状态
                    globalHardnessDeviceStatus = new DeviceStatusInfo 
                    { 
                        OperatingStatus = -1, 
                        AlarmStatus = -1, 
                        IsValid = false 
                    };
                    
                    System.Diagnostics.Debug.WriteLine("状态解析结果: 解析失败 - 数据格式错误或校验失败");
                    System.Diagnostics.Debug.WriteLine("==================");
                    
                    MessageBox.Show("无法获取设备状态，请检查设备连接！");
                    return;
                }

                // 更新全局设备状态
                globalHardnessDeviceStatus = statusInfo;
                
                // 控制台输出解析后的状态信息
                string operatingStatusDesc = ModBusRTUHelper.GetOperatingStatusDescription(statusInfo.OperatingStatus);
                string alarmStatusDesc = ModBusRTUHelper.GetAlarmStatusDescription(statusInfo.AlarmStatus);
                
                System.Diagnostics.Debug.WriteLine("状态解析结果:");
                System.Diagnostics.Debug.WriteLine($"  运行状态: {statusInfo.OperatingStatus} ({operatingStatusDesc})");
                System.Diagnostics.Debug.WriteLine($"  报警状态: {statusInfo.AlarmStatus} ({alarmStatusDesc})");
                System.Diagnostics.Debug.WriteLine($"  状态有效: {statusInfo.IsValid}");
                System.Diagnostics.Debug.WriteLine("==================");

                // 检查运行状态是否为"等待"（状态值0）
                if (statusInfo.OperatingStatus != 0)
                {
                    string statusDesc = ModBusRTUHelper.GetOperatingStatusDescription(statusInfo.OperatingStatus);
                    string alarmDesc = ModBusRTUHelper.GetAlarmStatusDescription(statusInfo.AlarmStatus);
                    
                    System.Diagnostics.Debug.WriteLine("状态检查结果: 设备状态异常");
                    System.Diagnostics.Debug.WriteLine($"  当前状态: {statusDesc} (需要等待状态)");
                    System.Diagnostics.Debug.WriteLine($"  报警状态: {alarmDesc}");
                    System.Diagnostics.Debug.WriteLine("==================");
                    
                    MessageBox.Show($"当前设备状态为：{statusDesc}\n报警状态：{alarmDesc}\n\n设备必须处于\"等待\"状态才能获取硬度检测值！", 
                                  "设备状态检查", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 检查报警状态
                if (statusInfo.AlarmStatus != 0)
                {
                    string alarmDesc = ModBusRTUHelper.GetAlarmStatusDescription(statusInfo.AlarmStatus);
                    
                    System.Diagnostics.Debug.WriteLine("状态检查结果: 设备存在报警");
                    System.Diagnostics.Debug.WriteLine($"  报警状态: {alarmDesc}");
                    System.Diagnostics.Debug.WriteLine("==================");
                    
                    MessageBox.Show($"设备存在报警：{alarmDesc}\n\n请先解决报警问题后再获取硬度检测值！", 
                                  "设备报警", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                
                System.Diagnostics.Debug.WriteLine("状态检查结果: 设备状态正常，可以读取硬度数据");
                System.Diagnostics.Debug.WriteLine("==================");

                // 设备状态正常，可以读取硬度数据
                byte[] hardnessCommand = ModBusRTUHelper.GenerateReadHardnessCommand();
                
                // 控制台输出发送的硬度读取命令
                System.Diagnostics.Debug.WriteLine("=== 串口发送命令 ===");
                System.Diagnostics.Debug.WriteLine($"设备类型: 滴定试剂法硬度检测仪");
                System.Diagnostics.Debug.WriteLine($"命令类型: 读取硬度数据");
                System.Diagnostics.Debug.WriteLine($"命令内容: {BitConverter.ToString(hardnessCommand).Replace("-", " ")}");
                System.Diagnostics.Debug.WriteLine($"命令描述: 读取硬度检测结果 (寄存器22-23)");
                System.Diagnostics.Debug.WriteLine($"ModBus格式: 设备地址=0x{hardnessCommand[0]:X2}, 功能码=0x{hardnessCommand[1]:X2}, 起始地址=0x{hardnessCommand[2]:X2}{hardnessCommand[3]:X2}, 寄存器数量={hardnessCommand[4] * 256 + hardnessCommand[5]}");
                System.Diagnostics.Debug.WriteLine($"发送时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                System.Diagnostics.Debug.WriteLine("==================");
                
                serialPort.Write(hardnessCommand, 0, hardnessCommand.Length);
                
                // 设置等待硬度数据响应的标志
                waitResponse = "hardness_data";
            }
            catch (Exception ex)
            {
                MessageBox.Show("处理设备状态响应时发生错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 直接读取硬度数据（跳过设备状态检查）
        /// </summary>
        private void readHardnessDataDirectly()
        {
            try
            {
                // 直接发送读取硬度数据的命令
                byte[] hardnessCommand = ModBusRTUHelper.GenerateReadHardnessCommand();
                
                // 控制台输出发送的硬度读取命令
                System.Diagnostics.Debug.WriteLine("=== 串口发送命令 ===");
                System.Diagnostics.Debug.WriteLine($"设备类型: 滴定试剂法硬度检测仪");
                System.Diagnostics.Debug.WriteLine($"命令类型: 直接读取硬度数据");
                System.Diagnostics.Debug.WriteLine($"命令内容: {BitConverter.ToString(hardnessCommand).Replace("-", " ")}");
                System.Diagnostics.Debug.WriteLine($"命令描述: 读取硬度检测结果 (寄存器22-23)");
                System.Diagnostics.Debug.WriteLine($"ModBus格式: 设备地址=0x{hardnessCommand[0]:X2}, 功能码=0x{hardnessCommand[1]:X2}, 起始地址=0x{hardnessCommand[2]:X2}{hardnessCommand[3]:X2}, 寄存器数量={hardnessCommand[4] * 256 + hardnessCommand[5]}");
                System.Diagnostics.Debug.WriteLine($"发送时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}");
                System.Diagnostics.Debug.WriteLine("==================");
                
                serialPort.Write(hardnessCommand, 0, hardnessCommand.Length);
                
                // 设置等待硬度数据响应的标志
                waitResponse = "hardness_data";
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"直接读取硬度数据时发生错误: {ex.Message}");
                MessageBox.Show("直接读取硬度数据时发生错误：" + ex.Message);
            }
        }

        private void 填充测试数据8ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            string indata = "55 01 00 00 00 41 00 06 40 C6 AA 6D 00 00 00 00 00 00 00 00 18 0B 11 0F 17 11 01 00 D1 02";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        private void btClearGrid_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows.Clear();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string indata = "55 03 00 00 00 41 00 06 40 EF 02 2A 00 00 00 00 00 00 00 00 18 0B 1D 09 36 27 01 00 41 00";
            operateReceiveData(indata.Replace(" ", ""), true);

            indata = "55 02 00 00 00 41 00 06 40 F6 FC 65 00 00 00 00 00 00 00 00 18 0C 02 0F 24 17 01 00 41 00";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        /// <summary>
        /// 根据数据包格式来判断是否缓冲区中的数据是一个完整的数据包。
        /// </summary>
        /// <param name="buffers"></param>
        /// <returns></returns>
        private bool isPackageCompleted(byte[] buffers)
        {
            return buffers.Length > 0 && buffers[0] == 0x55 && buffers.Length >= 30 && (buffers.Length - 7) % 23 == 0 && buffers.Length == Tools.ByteToUInt32(buffers, 1, true) * 23 + 7;
        }

        private void switchDeviceInInlandForeign(bool inland)
        {
            if ((inland))
            {
                rdoForeignDevice.Checked = false;
                rdoInlandDevice.Checked = true;

                currentDeivceMode = "inland";
                btReadData.Text = "从串口读取数据";

                grpUsbConnector.Enabled = false;
            }
            else
            {
                rdoInlandDevice.Checked = false;
                rdoForeignDevice.Checked = true;

                currentDeivceMode = "foreign";
                btReadData.Text = "从U盘读取数据";

                grpUsbConnector.Enabled = true;
            }
        }

        private void rdoInlandDevice_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoInlandDevice.Checked)
            {
                switchDeviceInInlandForeign(true);
                grpOperationArea.Enabled = true;
                //btInputManual.Enabled = true;
            }
        }

        private void rdoForeignDevice_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoForeignDevice.Checked)
            {
                string udiskPath = ConfigurationManager.AppSettings["UDiskPath"];
                if (udiskPath == null)
                {
                    MessageBox.Show(this, "未配置U盘的路径，请在配置文件中设置[UDiskPath]参数，值为数据文件在U盘中的路径！");

                    rdoInlandDevice.Checked = true;
                    return;
                }

                switchDeviceInInlandForeign(false);

                grpOperationArea.Enabled = false;

                //btInputManual.Enabled = false;
            }
        }

        private List<string> readDataFromUDisk()
        {
            List<string> readSuccessFileList = new List<string>();

            //判断是否配置了U盘的路径
            string udiskPath = ConfigurationManager.AppSettings["UDiskPath"];
            if (udiskPath == null)
            {
                MessageBox.Show(this, "未配置U盘的路径，请在配置文件中设置[UDiskPath]参数，值为数据文件在U盘中的路径！");
                return readSuccessFileList;
            }

            if (Directory.Exists(udiskPath) == false)
            {
                MessageBox.Show(this, "配置的U盘路径" + udiskPath + "不存在");
                return readSuccessFileList;
            }

            var csvFiles = new DirectoryInfo(udiskPath)
                .GetFiles("*.csv") // Get all CSV files
                .OrderBy(file => file.CreationTime) // Sort by creation time
                .ToArray(); // Convert to array if needed

            if (csvFiles.Length == 0)
            {
                MessageBox.Show(this, "在U盘数据路径下未找到任何扩展名为.csv的数据文件");
                return readSuccessFileList;
            }

            int startNo = dataGridView1.Rows.Count;

            for (int i = 0; i < csvFiles.Length; i++)
            {
                List<UDiskItemDataDto> results = ReadCsvData(csvFiles[i].FullName, 5, -1);

                for (int j = 0; j < results.Count; j++)
                {
                    UDiskItemDataDto currentItem = results[j];

                    ItemData item = new ItemData();
                    item.DeviceID = txtDeviceID.Text;
                    if (currentItem.SampleItemName == null || currentItem.SampleItemName.Trim().Equals(""))
                    {
                        MessageBox.Show(this, "参数名称不能为空！");
                        continue;
                    }

                    if (currentItem.SampleItemName.ToLower().Equals("yd"))
                    {
                        item.Name = "硬度";
                    }
                    else if (currentItem.SampleItemName.ToLower().Equals("tie"))
                    {
                        item.Name = "铁";
                    }
                    else
                    {
                        MessageBox.Show(this, "不支持的国外检测设备参数：" + currentItem.SampleItemName.Trim());
                        continue;
                    }

                    item.Unit = currentItem.Unit;

                    item.Concentration = Tools.RoundToEven(Double.Parse(currentItem.Result), 3).ToString("00000.000");
                    item.Absorbancy = Tools.RoundToEven(0, 3).ToString("0.0000");
                    item.Transparency = Tools.RoundToEven(0, 3).ToString("0.0000");

                    string dateFormat = "yyyy/MM/dd HH:mm:ss";

                    DateTime sampleDate = DateTime.Now;
                    if (DateTime.TryParseExact(currentItem.SampleDate, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out sampleDate))
                    {
                        item.TestDate = sampleDate;
                    }

                    item.UserNo = currentItem.OperatorId; ;
                    item.NO = (startNo + i + 1) + "";

                    deviceData.Items.Add(item);

                    readSuccessFileList.Add(csvFiles[i].FullName);
                }
            }

            return readSuccessFileList;
        }
        public List<UDiskItemDataDto> ReadCsvData(string filePath, int startLine, int endLine)
        {
            var resultList = new List<UDiskItemDataDto>();

            using (var reader = new StreamReader(filePath, Encoding.Unicode))
            {
                string line;
                int currentLine = 0;

                // 跳过前面的行，直到达到起始行
                while ((line = reader.ReadLine()) != null)
                {
                    currentLine++;

                    // 只处理指定范围内的行
                    if (currentLine < startLine) continue;
                    if (endLine > 0 && currentLine > endLine) break;

                    // 将当前行分割为字段
                    string[] parts = line.Split(',');

                    // 创建DTO对象并赋值（假设CSV列与DTO属性一一对应）

                    UDiskItemDataDto uDiskItemDataDto = new UDiskItemDataDto();
                    uDiskItemDataDto.SampleItemName = parts[0];
                    uDiskItemDataDto.SampleDate = parts[1];
                    uDiskItemDataDto.OperatorId = parts[2];
                    uDiskItemDataDto.SampleIdentifier = parts[3];
                    uDiskItemDataDto.SampleNumber = parts[4];
                    uDiskItemDataDto.SamplingDate = parts[5];
                    uDiskItemDataDto.Sampler = parts[6];
                    uDiskItemDataDto.Program = parts[7];
                    uDiskItemDataDto.Dilution = parts[8];
                    uDiskItemDataDto.BatchNumber = parts[9];
                    uDiskItemDataDto.ExpirationDate = parts[10];
                    uDiskItemDataDto.Result = parts[11];
                    uDiskItemDataDto.Unit = parts[12];
                    uDiskItemDataDto.Name = parts[13];
                    uDiskItemDataDto.HasError = parts[14];
                    uDiskItemDataDto.AQA = parts[15];
                    uDiskItemDataDto.AQA_BatchNumber = parts[16];


                    uDiskItemDataDto.AQA_ExpirationDate = parts[17];
                    uDiskItemDataDto.MultipleTests = parts[18];
                    uDiskItemDataDto.Notes = parts[19];

                    uDiskItemDataDto.Wavelength1 = parts[20];
                    uDiskItemDataDto.Value1 = parts[21];
                    uDiskItemDataDto.Unit1 = parts[22];

                    if (parts.Length > 24)
                    {
                        uDiskItemDataDto.Wavelength2 = parts[23];
                        uDiskItemDataDto.Value2 = parts[24];
                        uDiskItemDataDto.Unit2 = parts[25];
                    }

                    if (parts.Length > 27)
                    {
                        uDiskItemDataDto.Wavelength3 = parts[26];
                        uDiskItemDataDto.Value3 = parts[27];
                        uDiskItemDataDto.Unit3 = parts[28];
                    }

                    if (parts.Length > 30)
                    {
                        uDiskItemDataDto.Wavelength4 = parts[29];
                        uDiskItemDataDto.Value4 = parts[30];
                        uDiskItemDataDto.Unit4 = parts[31];
                    }

                    resultList.Add(uDiskItemDataDto);
                }
            }

            return resultList;
        }


        private void btUSBConnectDevice_Click(object sender, EventArgs e)
        {
            //向串口发送切换指令
            bool openSerialPortResult = initSerialPort();
            if (openSerialPortResult)
            {
                try
                {
                    grpOperationArea.Enabled = false;

                    buffers = new byte[0];
                    waitResponse = "{\"states\":0}";
                    byte[] sendBuffers = System.Text.UTF8Encoding.UTF8.GetBytes("{\"states\":0}");
                    serialPort.Write(sendBuffers, 0, sendBuffers.Length);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("报错位置7：" + ex.Message);
                }
            }
        }

        private void btUSBConnectComputer_Click(object sender, EventArgs e)
        {
            bool openSerialPortResult = initSerialPort();
            if (openSerialPortResult)
            {
                try
                {
                    grpOperationArea.Enabled = false;

                    buffers = new byte[0];
                    waitResponse = "{\"states\":1}";
                    byte[] sendBuffers = System.Text.UTF8Encoding.UTF8.GetBytes("{\"states\":1}");
                    serialPort.Write(sendBuffers, 0, sendBuffers.Length);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("报错位置8：" + ex.Message);
                }
            }
        }

        private void 填充现场数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string indata = "55 01 00 00 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 30 0B 01 00 84 00";
            operateReceiveData(indata.Replace(" ", ""), true);

            indata = "55 02 00 00 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 30 0B 01 0009 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 31 0F 01 00 0D 01";
            operateReceiveData(indata.Replace(" ", ""), true);

            indata = "55 03 00 00 0009 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 30 0B 01 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 180C 11 08 31 0F 01 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 31 1B 01 00 A2 01";
            operateReceiveData(indata.Replace(" ", ""), true);

            indata = "55 04 00 00 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 30 0B 01 0009 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 31 0F 01 00 09 00 01 00 00 00 00 00 00 00 00 0000 00 00 18 0C 11 08 31 1B 01 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 31 29 01 00 45 02";
            operateReceiveData(indata.Replace(" ", ""), true);

            indata = "55 05 00 00 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 30 0B 01 0009 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 31 0F 01 00 09 00 01 00 00 00 00 00 00 00 0000 00 00 00 18 0C 11 08 31 1B 01 00 09 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 31 29 01 0009 00 01 00 00 00 00 00 00 00 00 00 00 00 00 18 0C 11 08 31 35 01 00 F4 02";
            operateReceiveData(indata.Replace(" ", ""), true);
        }

        private void 模拟硬度检测仪数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 生成多条硬度测试数据
            string[] testDataList = HardnessTestData.GetTestDataList();
            string[] descriptions = HardnessTestData.GetTestDataDescriptions();
            
            // 显示数据选择对话框
            using (var dialog = new HardnessTestDataSelectionDialog(testDataList, descriptions))
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string selectedData = dialog.SelectedData;
                    if (!string.IsNullOrEmpty(selectedData))
                    {
                        // 调用 operateReceiveData 方法处理选中的数据
                        //operateReceiveData(selectedData, true);

                        byte[] buffersTemp = Tools.hexStringToByteArray(selectedData);

                        // 根据配置决定是否检查全局设备状态
                        string checkStatusConfig = ConfigurationManager.AppSettings["CheckHardnessDeviceStatus"];
                        bool shouldCheckStatus = true; // 默认检查状态
                        
                        if (!string.IsNullOrEmpty(checkStatusConfig))
                        {
                            bool.TryParse(checkStatusConfig, out shouldCheckStatus);
                        }
                        
                        if (shouldCheckStatus)
                        {
                            // 检查全局设备状态
                            if (globalHardnessDeviceStatus != null &&
                                        globalHardnessDeviceStatus.IsValid &&
                                        globalHardnessDeviceStatus.OperatingStatus == 0)
                            {
                                operateReceiveHardnessData(buffersTemp, false);
                                LogForm.getInstance().showLog("已处理模拟硬度数据");
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("模拟硬度数据被忽略:");
                                System.Diagnostics.Debug.WriteLine($"  原因: 设备状态不是'等待'");
                                System.Diagnostics.Debug.WriteLine($"  当前状态: {globalHardnessDeviceStatus?.OperatingStatus ?? -1}");
                                System.Diagnostics.Debug.WriteLine($"  状态有效: {globalHardnessDeviceStatus?.IsValid ?? false}");
                                System.Diagnostics.Debug.WriteLine("==================");
                                
                                LogForm.getInstance().showLog("设备状态不是'等待'，忽略模拟硬度数据");
                            }
                        }
                        else
                        {
                            // 不检查设备状态，直接处理模拟硬度数据
                            operateReceiveHardnessData(buffersTemp, false);
                            LogForm.getInstance().showLog("已处理模拟硬度数据（跳过状态检查）");
                        }
                    }
                }
            }
        }

        private void 模拟设备状态数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 显示设备状态选择对话框
            using (var dialog = new DeviceStatusSelectionDialog())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    string selectedStatus = dialog.SelectedStatus;
                    if (!string.IsNullOrEmpty(selectedStatus))
                    {
                        // 生成对应的设备状态响应数据
                        string statusData = ModBusRTUHelper.GenerateDeviceStatusResponseByDescription(selectedStatus);
                        
                        // 转换为字节数组
                        byte[] buffersTemp = Tools.hexStringToByteArray(statusData);
                        
                        // 模拟设备状态响应
                        handleDeviceStatusResponse(buffersTemp);
                        
                        LogForm.getInstance().showLog($"已模拟设备状态: {selectedStatus}");
                        
                        // 显示状态信息
                        var statusInfo = ModBusRTUHelper.ParseDeviceStatusResponse(buffersTemp);
                        if (statusInfo.IsValid)
                        {
                            string statusDesc = ModBusRTUHelper.GetOperatingStatusDescription(statusInfo.OperatingStatus);
                            string alarmDesc = ModBusRTUHelper.GetAlarmStatusDescription(statusInfo.AlarmStatus);
                            
                            MessageBox.Show($"模拟设备状态:\n运行状态: {statusDesc}\n报警状态: {alarmDesc}", 
                                          "设备状态模拟", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }
    }
}

